#include "restful_impl.h"
#include "utils_log.h"
#include "protocol.h"
#include "restful_diagnosis.h"
#include "websocket.h"

namespace El {
namespace Restful {

IRestfulService &IRestfulService::GetInstance()
{
    return RestfulServiceImpl::GetInstance();
}

RestfulServiceImpl &RestfulServiceImpl::GetInstance()
{
    static RestfulServiceImpl instance;
    return instance;
}

bool RestfulServiceImpl::Start()
{
    if (isRunning_) {
        return true;
    }
    isRunning_ = true;

    RegisterApiHandlers();

    RestfulDiagnosis::GetInstance().Start();

    WebSocketService::GetInstance().Start();

    return true;
}

void RestfulServiceImpl::Stop()
{
    if (!isRunning_) {
        return;
    }

    isRunning_ = false;
}

void RestfulServiceImpl::RegisterApiHandlers()
{
    protocol_ = Protocol::IProtocol::GetCustomInstance("restful"); // 使用工厂方法创建实例

    // 注册认证相关的API处理器
    WebServer::IHttpServer &server = WebServer::IHttpServer::GetInstance();

    // 将登录接口添加到免鉴权列表
    server.AddAuthExemptUrl("^/v1/jsonrpc2(/.*)?$");

    server.RegisterHandler("POST", "^/v1/jsonrpc2(/.*)?$",
                           [this](const WebServer::HttpRequest &req) { return ProcessHandlers(req); });
}

WebServer::HttpResponse RestfulServiceImpl::ProcessHandlers(const WebServer::HttpRequest &req)
{
    std::string id;
    std::string method;
    nlohmann::json params;

    EL_DEBUG("HttpRequest {} {}", req.uri, req.body);

    // 使用 ProtocolImpl 解析请求
    if (!protocol_->ParseRequest(req.body, id, method, params)) {
        EL_ERROR("Failed to parse WebSocket request on connection {}: {}", req.body);
        auto error_response = protocol_->CreateErrorResponse("", -32700, "Parse error");
        return WebServer::HttpResponse(400, "application/json", error_response);
    }

    // 鉴权处理
    if (method != "auth.getChallenge" && method != "auth.login" && method != "auth.refreshToken") {
        bool authenticated = false;
        auto authHeader = req.headers.find("Authorization");
        if (authHeader != req.headers.end()) {
            std::string authValue = authHeader->second;
            if (authValue.substr(0, 7) == "Bearer ") {
                std::string token = authValue.substr(7);
                authenticated = WebServer::IHttpServer::GetInstance().ValidateToken(token);
            }
        }
        if (!authenticated) {
            auto error_response =
                protocol_->CreateErrorResponse(id, 401, "Unauthorized", "Access token is missing or invalid");
            EL_DEBUG("Unauthorized request: {}", req.body);
            EL_DEBUG("error response: {}", error_response.c_str());

            // 返回401 Unauthorized响应
            return WebServer::HttpResponse(401, "application/json", error_response);
        }
    }

    // 使用 ProtocolImpl 处理消息
    nlohmann::json response;
    if (!protocol_->HandleMessage(id, method, params, response)) {
        return WebServer::HttpResponse(400, "application/json", response.dump());
    }
    return WebServer::HttpResponse(200, "application/json", response.dump());
}

} // namespace Restful
} // namespace El
